const Base = require('./base.js');
const API = require('co-wechat-api');
const fs = require('fs');
module.exports = class extends Base {
	constructor(ctx) {
		super(ctx);
		this.menu = this.model("weixin/menu");
		this.conf = this.model("weixin/config");
		this.reply = this.model("weixin/reply");
		
	}
	async indexAction() {
		if(this.isGet) {
			let gets = this.get();
			let wxid = "";
			let wxlist = await this.conf.select();

			if(!think.isEmpty(gets.id)) {
				let weixin = await this.conf.findOne(gets.id);
				if(!think.isEmpty(weixin)) {
					wxid = gets.id;
				}

			} else {
				if(!think.isEmpty(wxlist)) {
					wxid = wxlist[0].id;
				}

			}
			let menus = [];

			if(!think.isEmpty(wxid)) {
				menus = await this.menu.where({
					wxid: wxid
				}).order({
					sort: 'asc'
				}).select();
			}

			let firstMenus = [],
				secondMenus = {};

			menus.forEach((obj) => {
				if(obj && !obj.pid) {
					firstMenus.push(obj);
				} else if(obj) {
					let s = secondMenus[obj.pid] || [];
					if(JSON.stringify(s).indexOf(JSON.stringify(obj)) < 0) {
						s.push(obj);
					}
					secondMenus[obj.pid] = s;
				}
			});

			this.assign("wxid", wxid);
			this.assign("wxlist", wxlist);
			this.assign("menus", menus);
			this.assign("firstWxMenus", firstMenus);
			this.assign("secondWxMenus", secondMenus);

			return this.display();
		}

	}
	async addAction() {

		if(this.isGet) {
			let gets = this.get();
			let wxid = gets.id;
			let menus = await this.menu.where({
				wxid: wxid,
				pid: 0
			}).order({
				sort: 'asc'
			}).select();
			this.assign('wxid', wxid);
			this.assign('menus', menus);
			return this.display();
		}

		if(this.isPost) {
			let posts = this.post();
			if(!posts.wxid) {
				return this.fail("请配置公众号");
			}
			let pid = posts.pid;

			let user = await this.session("user");
			let insertId = await this.menu.add({
				pid: posts.pid,
				name: posts.name,
				type: posts.type,
				key: posts.key,
				url: posts.url,
				sort: 0,
				create_by: user.user_id,
				create_time: new Date().valueOf(),
				wxid: posts.wxid

			});

			if(think.isEmpty(insertId)) {
				return this.fail("添加失败");
			}
			if(pid > 0) {
				await this.menu.where({
					id: pid
				}).update({
					hasChildren: 1
				});
			}
			return this.success("添加成功");

		}

	}
	async checkAction() {
		if(this.isPost) {
			let posts = this.post();
			if(posts.pid == 0) {
				let num = await this.menu.where({
					pid: 0,
					wxid: posts.wxid
				}).count();
				if(num > 2) {
					return this.fail("只可设置三个一级菜单");

				}
			} else {
				let num = await this.menu.where({
					pid: posts.pid,
					wxid: posts.wxid
				}).count();
				if(num > 4) {
					return this.fail("只可设置五个二级菜单");

				}

			}
			return this.success();

		}

	}

	async keywordAction() {
		if(this.isGet) {
			let gets = this.get();
			this.assign("wxid", gets.id);
			return this.display();

		}
		if(this.isPost) {

			let posts = this.post();
			let where = {
				type: "keyword"
			};
			if(!think.isEmpty(posts.wxid)) {
				where.wxid = posts.wxid;
			}

			const data = await this.reply.dataTable(posts, where);
			return this.json(data);

		}
	}

	async editAction() {

		if(this.isGet) {
			let gets = this.get();
			let menu = await this.menu.findOne(gets.id);
			let menus = await this.menu.where({
				wxid: menu.wxid,
				pid: 0
			}).order({
				sort: 'asc'
			}).select();
			this.assign('menu', menu);
			this.assign('menus', menus);
			return this.display();
		}

		if(this.isPost) {
			let posts = this.post();

			let update = await this.menu.setOne(posts.id, {
				pid: posts.pid,
				name: posts.name,
				type: posts.type,
				key: posts.key,
				url: posts.url

			});

			if(think.isEmpty(update)) {
				return this.fail("修改失败");
			}

			return this.success("修改成功");

		}

	}

	async deleteAction() {

		let posts = this.post();
		let menu = await this.menu.where({
			id: posts.id
		}).find();
		if(menu.hasChildren) {
			return this.fail("请先删除子菜单");
		}
		await this.menu.where({
			id: menu.id
		}).delete();
		let count = await this.menu.where({
			pid: menu.pid
		}).count();
		if(count == 0) {
			await this.menu.where({
				id: menu.pid
			}).update({
				hasChildren: 0
			});
		}

		return this.success("删除成功");

	}

	async sortAction() {

		let i = 0,
			j = 0;
		console.log(this.post());
		let ids = JSON.parse(this.post("ids"));
		let self = this;

		ids.forEach(async(f) => {
			i++;
			let fid = f.id;
			await self.menu.setOne(fid, {
				sort: i
			});
			if(f.children) {
				f.children.forEach(async(s) => {
					j++;
					let sid = s.id;
					await self.menu.setOne(sid, {
						sort: j
					});

				});

			}
		});
		return this.success("修改成功");

	}

	async pushAction() {

		let posts = this.post();
		if(!posts.wxid) {
			return this.fail("请配置公众号");
		}

		let menus = await this.menu.where({
			wxid: posts.wxid
		}).order({
			sort: 'asc'
		}).select();
		let firstMenus = [],
			secondMenus = {};
		menus.forEach((obj) => {
			if(obj.pid == 0) {
				firstMenus.push(obj);
			} else {
				let s = secondMenus[obj.pid] || [];
				if(JSON.stringify(s).indexOf(JSON.stringify(obj)) < 0) {
					s.push(obj);
				}
				secondMenus[obj.pid] = s;
			}
		});
		let m = [];
		if(think.isEmpty(firstMenus)) {
			return this.fail("推送失败");
		}

		firstMenus.forEach((obj) => {
			let mm = {};
			if(obj.hasChildren) {
				let submenu = [];
				mm.name = obj.name;
				if(secondMenus[obj.id]) {
					secondMenus[obj.id].forEach((secondMenu) => {
						let submenuObj = {};
						if(secondMenu.type == 'view') {
							submenuObj.type = secondMenu.type;
							submenuObj.name = secondMenu.name;
							submenuObj.url = secondMenu.url;
						} else if(secondMenu.type == 'click') {
							submenuObj.type = secondMenu.type;
							submenuObj.name = secondMenu.name;
							submenuObj.key = secondMenu.key;
						} else {
							submenuObj.name = secondMenu.name;
						}
						submenu.push(submenuObj);
					});
					mm.sub_button = submenu;
				}
				m.push(mm);
			} else {
				let submenuObj = {};
				if(obj.type == 'view') {
					submenuObj.type = obj.type;
					submenuObj.name = obj.name;
					submenuObj.url = obj.url;
				} else if(obj.type == 'click') {
					submenuObj.type = obj.type;
					submenuObj.name = obj.name;
					submenuObj.key = obj.key;
				} else {
					submenuObj.name = obj.name;
				}
				m.push(submenuObj);
			}
		});
		let wxmenu = {
			button: m
		};
		let api = await this.wechatApi(posts.wxid);
		let result = await api.createMenu(wxmenu); 
		if(result.errcode == '0') {
			return this.success("推送成功");
		} else {
			return this.fail("推送失败");
		}

	}
};